#!/usr/bin/env python3
"""
个人任务管理器演示脚本
展示系统的主要功能
"""

import os
import sys
import time
from datetime import datetime, timedelta

# 添加项目根目录到 Python 路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from services.task_service import TaskService
from models.database import DatabaseManager
from config.settings import settings


def print_separator(title=""):
    """打印分隔线"""
    print("\n" + "=" * 60)
    if title:
        print(f"🎯 {title}")
        print("=" * 60)


def wait_for_user():
    """等待用户按键继续"""
    input("\n按 Enter 键继续...")


def demo_basic_operations():
    """演示基本操作"""
    print_separator("基本任务操作演示")
    
    # 初始化服务
    db_manager = DatabaseManager(settings.get_database_path())
    task_service = TaskService(db_manager)
    
    print("📝 1. 添加任务")
    
    # 添加几个示例任务
    tasks_to_add = [
        {
            "title": "学习Python高级特性",
            "description": "深入学习装饰器、生成器、上下文管理器等",
            "priority": "high",
            "category": "学习",
            "due_date": datetime.now() + timedelta(days=7)
        },
        {
            "title": "完成项目文档",
            "description": "编写API文档和用户手册",
            "priority": "medium",
            "category": "工作",
            "due_date": datetime.now() + timedelta(days=3)
        },
        {
            "title": "健身锻炼",
            "description": "每周至少3次有氧运动",
            "priority": "low",
            "category": "健康",
            "due_date": datetime.now() + timedelta(days=1)
        }
    ]
    
    for task_data in tasks_to_add:
        success, message, task = task_service.add_task(**task_data)
        if success:
            print(f"✅ {message}")
            print(f"   📝 {task}")
        else:
            print(f"❌ {message}")
    
    wait_for_user()
    
    print("\n📋 2. 查看任务列表")
    tasks = task_service.list_tasks()
    if tasks:
        print(f"找到 {len(tasks)} 个任务:")
        for task in tasks:
            status_icon = "✅" if task.status == "completed" else "⏳" if task.status == "todo" else "🔄"
            priority_icon = "🔴" if task.priority == "high" else "🟡" if task.priority == "medium" else "🟢"
            print(f"   {status_icon} [{task.id:2d}] {priority_icon} {task.title}")
            print(f"       分类: {task.category or '无'} | 截止: {task.due_date or '无'}")
    else:
        print("暂无任务")
    
    wait_for_user()
    
    print("\n🔍 3. 搜索任务")
    search_results = task_service.search_tasks("Python")
    if search_results:
        print(f"搜索 'Python' 找到 {len(search_results)} 个任务:")
        for task in search_results:
            print(f"   📝 [{task.id}] {task.title}")
    else:
        print("未找到匹配的任务")
    
    wait_for_user()
    
    print("\n✏️ 4. 编辑任务")
    if tasks:
        first_task = tasks[0]
        success, message = task_service.edit_task(
            first_task.id, 
            status="in_progress",
            description="已开始学习，进展顺利"
        )
        if success:
            print(f"✅ {message}")
            updated_task = task_service.get_task(first_task.id)
            print(f"   📝 更新后: {updated_task}")
        else:
            print(f"❌ {message}")
    
    wait_for_user()
    
    print("\n📊 5. 查看统计信息")
    stats = task_service.get_task_statistics()
    print("任务统计:")
    print(f"   📋 总任务数: {stats.get('total', 0)}")
    print(f"   ⏳ 待办任务: {stats.get('todo', 0)}")
    print(f"   🔄 进行中任务: {stats.get('in_progress', 0)}")
    print(f"   ✅ 已完成任务: {stats.get('completed', 0)}")
    print(f"   📈 完成率: {stats.get('completion_rate', 0)}%")
    
    return task_service


def demo_advanced_features(task_service):
    """演示高级功能"""
    print_separator("高级功能演示")
    
    print("🔍 1. 高级过滤")
    
    # 按优先级过滤
    high_priority_tasks = task_service.advanced_search({
        'priority': ['high', 'medium'],
        'sort_by': 'priority',
        'sort_direction': 'DESC'
    })
    
    if high_priority_tasks:
        print(f"高/中优先级任务 ({len(high_priority_tasks)} 个):")
        for task in high_priority_tasks:
            priority_icon = "🔴" if task.priority == "high" else "🟡"
            print(f"   {priority_icon} [{task.id}] {task.title} ({task.category})")
    
    wait_for_user()
    
    print("\n📅 2. 日期相关查询")
    
    # 过期任务
    overdue_tasks = task_service.get_overdue_tasks()
    if overdue_tasks:
        print(f"⚠️  过期任务 ({len(overdue_tasks)} 个):")
        for task in overdue_tasks:
            print(f"   📝 [{task.id}] {task.title} (截止: {task.due_date})")
    else:
        print("✅ 没有过期任务")
    
    # 即将到期的任务
    upcoming_tasks = task_service.get_upcoming_tasks(days=7)
    if upcoming_tasks:
        print(f"\n📅 未来7天内到期的任务 ({len(upcoming_tasks)} 个):")
        for task in upcoming_tasks:
            print(f"   📝 [{task.id}] {task.title} (截止: {task.due_date})")
    
    wait_for_user()
    
    print("\n📊 3. 数据导出演示")
    
    # 导出为 JSON
    success, message, data = task_service.export_tasks('json')
    if success:
        print(f"✅ {message}")
        print(f"   📄 数据长度: {len(data)} 字符")
        
        # 保存到文件
        with open('demo_export.json', 'w', encoding='utf-8') as f:
            f.write(data)
        print("   💾 已保存到 demo_export.json")
    else:
        print(f"❌ {message}")


def demo_interactive_mode():
    """演示交互模式"""
    print_separator("交互模式演示")
    
    print("🎮 交互模式可以让你实时操作任务管理器")
    print("💡 常用命令:")
    print("   • add \"任务标题\" -p high -c 分类")
    print("   • list --status todo")
    print("   • search \"关键词\"")
    print("   • complete 任务ID")
    print("   • stats")
    print("   • help")
    print("   • quit")
    
    print("\n🚀 要进入交互模式，请运行:")
    print("   python main.py")
    print("   或")
    print("   python main.py interactive")


def main():
    """主演示函数"""
    print("🎯 个人任务管理器功能演示")
    print("=" * 60)
    print("本演示将展示任务管理器的主要功能")
    print("包括任务的增删改查、搜索过滤、统计报告等")
    
    wait_for_user()
    
    try:
        # 基本操作演示
        task_service = demo_basic_operations()
        
        # 高级功能演示
        demo_advanced_features(task_service)
        
        # 交互模式说明
        demo_interactive_mode()
        
        print_separator("演示完成")
        print("🎉 演示完成！")
        print("💡 现在你可以:")
        print("   1. 运行 'python main.py' 开始使用")
        print("   2. 查看 'USAGE.md' 了解详细用法")
        print("   3. 查看 'README.md' 了解项目详情")
        
        # 清理演示文件
        if os.path.exists('demo_export.json'):
            os.remove('demo_export.json')
            print("\n🧹 已清理演示文件")
        
    except Exception as e:
        print(f"\n❌ 演示过程中出现错误: {str(e)}")
        print("请检查系统配置或联系开发者")


if __name__ == "__main__":
    main()